var express = require('express');
var router = express.Router();
const multer = require('multer');
const fs = require('fs');
/* GET users listing. */
const path = require('path');
const upload = multer({ dest: path.join(path.dirname(__dirname), 'saveImg')});

router.post('/upimgs', upload.single('img'), (req, res) => {
  // console.log(req.file);
  let num = 200 * 1024;
  if (req.file.size > num) {
    res.send({ status: 200, success: false, msg: '上传失败，图片过大！'});
    return;
  }
  fs.readFile(req.file.path, (err, data) => { // 读取上传的被编码的文件
    let imgName = `${new Date().getTime()}.${req.file.originalname.split('.')[req.file.originalname.split('.').length-1]}`;
    fs.writeFile('public/images/' + `${imgName}`, data, () => {
      fs.unlink(req.file.path, (err) => {})
      res.send({ status: 200, success: true, msg: '上传成功！',data:{
        url:`/images/${imgName}`
      }});
    })
  })
});

module.exports = router;
